package com.example.demo.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.common.Constants;
import com.example.demo.common.Result;
import com.example.demo.dto.UserDTO;
import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import com.example.demo.utils.TokenUtils;
import com.sun.deploy.net.URLEncoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 查询所有的用户
     * @return
     */
    @GetMapping
    public List<User> index(){
        return userService.list();
    }

    /**
     * 根据用户名查询相关信息
     * @return
     */
    @GetMapping("/username/{username}")
    public User findUserInfo(@PathVariable String username){
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",username);

        return userService.getOne(queryWrapper);
    }

    /**
     * 用户登录
     * @param userDTO
     * @return
     */
    @PostMapping("/login")
    public Result login(@RequestBody UserDTO userDTO){
        String username = userDTO.getUsername();
        String password = userDTO.getPassword();
        if (StrUtil.isBlank(username) || StrUtil.isBlank(password)){
            return Result.error(Constants.SYSTEM_BAD_REQUEST,"参数错误");
        }
        UserDTO dto = userService.login(userDTO);

        return Result.success(dto);
    }

    /**
     * 用户新增及修改
     * @param user
     * @return
     */
    @PostMapping
    public boolean userSave(@RequestBody User user){
        return userService.saveUser(user);
    }

    /**
     * 用户注册
     * @param userDTO
     * @return
     */
    @PostMapping("/register")
    public Result register(@RequestBody UserDTO userDTO){

        String username = userDTO.getUsername();
        String password = userDTO.getPassword();
        if (StrUtil.isBlank(username) || StrUtil.isBlank(password)){
            return Result.error(Constants.SYSTEM_BAD_REQUEST,"参数错误");
        }

        return Result.success(userService.register(userDTO));

    }

    /**
     * 根据id删除相关的用户信息
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    public boolean delete(@PathVariable Integer id){
        return userService.removeById(id);
    }

    /**
     * 批量删除相关的用户信息
     * @param ids
     * @return
     */
    @PostMapping("/del/batch")
    public boolean deleteBatch(@RequestBody List<Integer> ids){
        return userService.removeByIds(ids);
    }

    /**
     * mybatis 的分页查询
     * @param
     * @return
     */
//    @GetMapping("/page")
//    public Map<String,Object> findPage(@RequestParam Integer pageNum,
//                                       @RequestParam Integer pageSize,
//                                       String username,
//                                       String email,
//                                       String address){
//        pageNum = (pageNum-1) * pageSize;
//        List<User> data = userMapper.selectPage(pageNum,pageSize,username,email,address);
//        Integer total = userMapper.selectTotal(username,email,address);
//        Map<String,Object> res = new HashMap<>();
//        res.put("data",data);
//        res.put("total",total);
//        return res;
//
//    }


    /**
     * mabtisplus 的分页查询
     */
    @GetMapping("/page")
    public IPage<User> findPage(@RequestParam Integer pageNum,
                                @RequestParam Integer pageSize,
                                @RequestParam(defaultValue = "") String username,
                                @RequestParam(defaultValue = "") String email,
                                @RequestParam(defaultValue = "") String address){
        IPage<User> page = new Page<>(pageNum,pageSize);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        // 添加排除条件
        if (!username.isEmpty()) {
            queryWrapper.like("username", username);
        }
        if (!email.isEmpty()) {
            queryWrapper.like("email", email);
        }
        if (!address.isEmpty()) {
            queryWrapper.like("address", address);
        }

        IPage<User> userPage = userService.page(page, queryWrapper);

        return userPage;

    }

    /**
     * 用户信息导出到一个excle中
     * @param response
     * @throws Exception
     */
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws Exception {
        //获取user对象列表
        List<User> list = userService.list();
        //使用ExcelUtil工具类的getWriter方法创建一个ExcelWriter对象，参数true表示创建一个包含表头的Excel写入器
        ExcelWriter writer = ExcelUtil.getWriter(true);
        //设置别名
//        writer.addHeaderAlias("username", "用户名");
//        writer.addHeaderAlias("password", "密码");
//        writer.addHeaderAlias("nickname", "昵称");
//        writer.addHeaderAlias("email", "邮箱");
//        writer.addHeaderAlias("phone", "电话");
//        writer.addHeaderAlias("address", "地址");
//        writer.addHeaderAlias("createTime", "创建时间");
        //使用write方法将用户列表list写入Excel，第二个参数true表示写入数据时包含表头
        writer.write(list,true);
        //设置HTTP响应的内容类型为Excel文件（.xlsx格式），并指定字符集为UTF-8
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        //使用URLEncoder对文件名"用户信息"进行URL编码
        String fileName = URLEncoder.encode("用户信息", "UTF-8");

        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
        //从HttpServletResponse对象中获取输出流，用于将Excel文件数据发送给客户端
        ServletOutputStream out = response.getOutputStream();
        //将Excel写入器中的数据刷新到输出流out中
        writer.flush(out, true);
        out.close();
        writer.close();

    }

    /**
     * 导入
     * @param file
     * @return
     * @throws Exception
     */

    @PostMapping("/import")
    public boolean imp(MultipartFile file) throws Exception{
        //从上传的文件中获取输入流
        InputStream inputStream = file.getInputStream();
        //使用ExcelUtil工具类的getReader方法创建一个ExcelReader对象，该对象用于读取Excel文件的内容
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        //调用read方法读取Excel文件的内容。参数1可能表示跳过第一行（通常是表头），只读取数据行
        List<List<Object>> list = reader.read(1);
        //创建一个新的ArrayList实例，用于存储从Excel文件中读取的用户信息
        List<User> users = CollUtil.newArrayList();
        for (List<Object> row : list) {
            User user = new User();
            user.setUsername(row.get(0).toString());
            user.setPassword(row.get(1).toString());
            user.setNickname(row.get(2).toString());
            user.setEmail(row.get(3).toString());
            user.setPhone(row.get(4).toString());
            user.setAddress(row.get(5).toString());
            users.add(user);
        }
        //将用户列表中的数据批量保存到数据库中
        userService.saveBatch(users);
        return true;

    }

}
